#!/usr/bin/python
# -*- coding: UTF-8 -*-
import requests
import os


def download_ts(url, path):
    ts = requests.get(url)
    if ts.ok:
        index = path.rindex("/")
        folder = path[:index]
        if not os.path.exists(folder):
            os.mkdir(folder)

        with open(path, 'wb') as f:
            f.write(ts.content)
        return True
    else:
        return False


if __name__ == '__main__':
    total_length = 6
    m3u8_url = "https://tudou.com-l-tudou.com/20190517/18701_8327f1c3/1000k/hls/index.m3u8"
    url = "https://tudou.com-l-tudou.com/20190517/18701_8327f1c3/1000k/hls/f8a1018f6ff{second}.ts"
    file = "G:/video/f8a1018f6ff{second}.ts"
    for i in range(999999):
        second = str(i).rjust(total_length, '0')
        ts_url = url.format(second=second)
        ts_file = file.format(second=second)
        if not download_ts(ts_url, ts_file):
            break




